package leeon.bbsbrower.views;

import ipworks.IPWorksException;
import leeon.bbsbrower.actions.BBSMailAction;

import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.KeyListener;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.part.ViewPart;

public class MailConView extends ViewPart {
	public static final String ID = "bbsbrower.view.mailcon";

	private Text text = null;
	
	//从哪一篇信进入
	private static int mail = 0;
	
	/**
	 * This is a callback that will allow us to create the viewer and initialize
	 * it.
	 */
	public void createPartControl(Composite parent) {		
		
		//信件内容数据
		text = new Text(parent, SWT.V_SCROLL|SWT.READ_ONLY);
		text.setFont(ApplicationWorkbenchWindowAdvisor.listFont);		
				
		//上下左右的事件
		text.addKeyListener(new KeyListener() {

			public void keyPressed(KeyEvent e) {
				//左
				if (e.keyCode == SWT.ARROW_LEFT) {
					actionToMailList();
					e.doit = false;
				} else if (e.keyCode == SWT.ARROW_RIGHT) {
					e.doit = false;
				} else if (e.character == 'r') {
					actionReMail();
					e.doit = false;
				}
			}

			public void keyReleased(KeyEvent e) {}
			
		});
	}
	
	
	/**
	 * 回信件列表
	 */
	private void actionToMailList() {		
		//跳转信件列表界面
		IWorkbenchPage page = this.getViewSite().getPage();
		page.hideView(this);
		try {
			MailListView mail = (MailListView)page.showView(MailListView.ID);
			mail.refreshData(-1, MailConView.mail, null);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 回信
	 *
	 */
	private void actionReMail() {
		String id = MailListView.mails[mail].getSender();
		String title = MailListView.mails[mail].getTitle();
		
		IWorkbenchPage page = this.getViewSite().getPage();
		page.hideView(this);
		try {
			SendMailView mail = (SendMailView)page.showView(SendMailView.ID);
			mail.refreshData(2, id, title, null, MailConView.mail);
		} catch (PartInitException e) {
			e.printStackTrace();
		}
	}
	
	public void refreshData(int mail, String url) {
		//根据url提取信件
		MailConView.mail = mail;
		
		//设定值
		try {
			text.setText(BBSMailAction.getMailContentByURL(url));
		} catch (IPWorksException e) {
			MessageDialog.openError(this.getViewSite().getShell(), "错误信息", e.toString());
			e.printStackTrace();
		}
		
		ApplicationActionBarAdvisor.setStatusLine();
	}

	/**
	 * Passing the focus request to the viewer's control.
	 */
	public void setFocus() {
		text.setFocus();
	}
}